<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-10-11
 * Time: 10:27
 */

namespace App\Http\Controllers\Api\V1\Front\Wx;


use App\Http\Controllers\Controller;
use App\Libs\Contracts\PayMent\Wxpay\JsApiNativePay;
use App\Libs\httpUtil;
use App\Libs\WXBizDataCrypt;
use App\Models\AreaTotal;
use App\Models\DeviceSetting;
use App\Models\User;
use App\Services\Front\AreaTotalService;
use App\Services\Front\IncomeService;
use App\Services\Wx\AliService;
use Illuminate\Http\Request;


class WxController extends Controller
{


    /**
     * 通过code获取用户详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfoByCode(Request $request)
    {
        $code = $request->code;
        if (!$code) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . env("WX_APPID") . "&secret=" . env("WX_APPKEY") . "&code=" . $code . "&grant_type=authorization_code";
        $http = new httpUtil();
        $accessToken = $http->http_get($url);
        if (!$accessToken) {
            return $this->apiResponse('', config('errorCode.INVALID_CODE_PARAMS'));
        }
        $result = json_decode($accessToken, true);

        if (!empty($result['errcode'])) {
            \Log::error(' WxController getUserInfoByCode  code ' . $accessToken);
            return $this->apiResponse('', config('errorCode.INVALID_CODE_PARAMS'));
        }
        $data['openid'] = $result['openid'] ;
        return $this->apiResponse($data);

    }

    /**
     *  微信JS权限配置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getWxConfig(Request $request)
    {

        $server = new AliService();

        $url = $request->url;
        if (!$url) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $ticket = $server->getJsapiTicket();
        $noncestr = noncestr(8);
        $timestamp = time();
        $signRaw = "jsapi_ticket=$ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $sign = sha1($signRaw);
        $result['appId'] = env("APPID");
        $result['nonceStr'] = $noncestr;
        $result['timestamp'] = $timestamp;
        $result['signature'] = $sign;
        return $this->apiResponse($result);
    }

    /**
     * 微信小程序登录
     */

    public function login(Request $request)
    {
        $code = $request->code;
        if (!$code) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        //接口地址
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . env("APPID") . "&secret=" . env("AppSecret") . "&js_code=" . $code . "&grant_type=authorization_code";
        $http = new httpUtil();
        $data = $http->http_get($url);
        if (!$data) {
            return $this->apiResponse('', config('errorCode.INVALID_CODE_PARAMS'));
        }
        $result = json_decode($data, true);

        if (!array_key_exists('openid', $result)) {
            return $this->apiResponse('', config('errorCode.SERVER_EXCEPTION'));
        }
        $session_key = $result['session_key'];
        cache(['session_key' . $result['openid'] => $session_key], 3);

        $user = User::where('openId', $result['openid'])->first();
        if (!$user) {
            $data = [];
            $data['openId'] = $result['openid'];
            $data['session_key'] = 'session_key' . $data['openId'];
            return $this->apiResponse($data);
        }
        return $this->apiResponse($user);
    }

    public function register(Request $request)
    {
        $code = ($request->code);
        $iv = ($request->iv);
        $encryptedData = ($request->encryptedData);
        if (!$code) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        //接口地址
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxff89e95fa3fd1b2e&secret=052b24281b1b32baf2d011a584dbe0b5&js_code=" . $code . "&grant_type=authorization_code";

        $http = new httpUtil();
        $data = $http->http_get($url);
        if (!$data) {
            return $this->apiResponse('', config('errorCode.INVALID_CODE_PARAMS'));
        }
        $result = json_decode($data, true);

        if (!array_key_exists('openid', $result)) {
            return $this->apiResponse('', [
                'errorCode' => "11011",
                'errorMessage' => $result['errmsg']]);
        }
        $openid = $result['openid'];
        $sessionKey = $result['session_key'];
        $appid = "wxff89e95fa3fd1b2e";
        $pc = new WXBizDataCrypt($appid, $sessionKey);

        $errCode = $pc->decryptData($encryptedData, $iv, $data1);

        if ($errCode == 0) {
            $result = json_decode($data1, true);
            $user = User::where('openId', $openid)->first();
            if ($user) {
                User::where('openId', $openid)->update(['nickName' => $result['nickName'], 'avatarUrl' => $result['avatarUrl']]);
                $user = User::where(['userId' => $user['userId']])->first();
            } else {
                $user['openId'] = $openid;
                $user['nickName'] = $result['nickName'];
                $user['avatarUrl'] = $result['avatarUrl'];
                $user['createTime'] = date('Y-m-d H:i:s');
                $userId = User::insertGetId($user);
                DeviceSetting::create(['userId' => $userId]);
                $result['userId'] = $userId;
                $user = User::where(['userId' => $result['userId']])->first();
            }
            return $this->apiResponse($user);
        } else {
            return $this->apiResponse('', [
                'errorCode' => $errCode,
                'errorMessage' => $errCode]);
        }

    }

    /**
     *
     * 推送消息
     */
    public function PushMessage(Request $request)
    {
        $openid = $request->openid;
        $token = new AliService();
        $access_token = $token->getAccessToken();
        $push_url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $access_token;
        $parmArr = [
            //touser template_id page form_id data color
            "touser" => $openid,
            "template_id" => "kVd63lsQ5XXrm_bmi5D1bxujY1VNCmtNNAOehbmyP5A",
            "page" => '', //跳转页面所用
            'form_id' => '',  //form-id
            "data" => [
                "keyword1" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                "keyword2" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                "keyword3" => [
                    "value" => '',
                    "color" => "#173177"
                ],
                "keyword4" => [
                    "value" => '',
                    "color" => "#173177"
                ],
            ]
        ];

        $paramObj = json_encode($parmArr);
        $res = [];
        $http = new httpUtil();
        $status = $http->http_post($push_url, $paramObj);
        $status = json_decode($status, true);
    }

    /**
     * 获取微信手机号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPhone(Request $request)
    {
        $iv = $request->iv;
        $encryptedData = $request->encryptedData;
        $code = $request->code;
        if (!$code || !$iv || !$encryptedData) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }

        //接口地址
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . env("APPID") . "&secret=" . env("AppSecret") . "&js_code=" . $code . "&grant_type=authorization_code";
        $http = new httpUtil();
        $data = $http->http_get($url);

        if (!$data) {
            return $this->apiResponse('', config('errorCode.INVALID_CODE_PARAMS'));
        }
        $result = json_decode($data, true);
        if (!array_key_exists('openid', $result)) {
            return $this->apiResponse('', config('errorCode.SERVER_EXCEPTION'));
        }
        $sessionKey = $result['session_key'];

        $pc = new WXBizDataCrypt(env("APPID"), $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $res);
        if ($errCode != 0) {
            return $this->apiResponse('', config('errorCode.SERVER_EXCEPTION'));
        }

        $res = json_decode($res, true);

        return $this->apiResponse($res);
    }


    public function wxpay(Request $request)
    {
        $orderNo = $request->orderNo;
        $userId = $request->userId;
        $user = User::find($userId);
        $orderObj = ActivityOrder::where('orderNo', $orderNo)->first();

        $order['body'] = "活动支付";
        $order['openId'] = $user['openId'];
        $order['totalFee'] = $orderObj['totalPrice'];
        $order['orderNo'] = $orderNo;
        $result = JsApiNativePay::JsApiNativePay($order);
        $timestamp = time();
        $signType = "MD5";
        $package = 'prepay_id=' . $result['prepay_id'];
        $nonceStr = nonceStr();
        $resSignRaw = "appId=" . env("APPID") . "&nonceStr=" . $nonceStr . "&package=" . $package . "&signType=" . $signType . "&timeStamp=" . $timestamp . "&key=" . env("WX_KEY");
        $resSign = md5($resSignRaw);
        $responseOrder['appId'] = env("APPID");
        $responseOrder['package'] = $package;
        $responseOrder['paySign'] = $resSign;
        $responseOrder['nonceStr'] = $nonceStr;
        $responseOrder['signType'] = $signType;
        $responseOrder['timeStamp'] = $timestamp;
        $USERID = $request->USERID;
        return $this->apiResponse($USERID, $responseOrder, 0, $request->userStatusFlag);
    }

}